<?php

namespace app\admin\controller;


use app\common\Esclient;
use app\common\model\AdminLogModel;
use app\common\model\AdminModel;
use app\common\model\GroupChatModel;
use app\common\model\GroupChatUserModel;
use app\common\model\LiveRoomBanneduserModel;
use app\common\model\LiveRoomManagerModel;
use app\common\model\MgrChatModel;
use app\common\model\PrivateChatSessionModel;
use app\common\model\UserModel;
use think\Db;
use app\service\GroupchatService;
use app\service\PrivatechatService;
use gogrpc\TencentTimServer;
use think\facade\Cache;
use think\db\Query;
use think\facade\Request;
use think\Validate;

/**
 * 群聊模块
 * @date 2022-12-19
 */
class GroupchatController extends BaseController
{

    /**
     * 群聊列表
     * @return mixed
     */
    public function index()
    {
        // 搜索主播昵称和id
        $search_name = Request::get('search_name');
        $result = GroupchatService::getAnchorList($this->userinfo->roleid, $this->admin_id, $search_name);
        if (Request::isAjax()) {
            return json(['count' => count($result), 'list' => $result]);
        }
        $this->assign('list', $result);
        $this->assign('count', count($result));
        return $this->fetch();
    }

    /**
     * 私聊详情
     * @return mixed
     */
    public function chat_info()
    {
        $anchor_id = Request::get('anchor_id', 0, 'intval');
        // 查询私聊历史信息
        $where = [
            ['anchor_id', '=', $anchor_id],
            ['status', '=', 0],
        ];

        $group_list = GroupChatModel::with([
            'anchor' => function ($query) {
                $query->field('id,nick_name');
            },
        ])->where($where)->order('id', 'DESC')
            ->select()
            ->toArray();

        $unreadMessage = Cache::store('redis')->handler()->hGetAll('GROUPCHAT:MSG:NUM') ?: [];
        if (!Cache::store('redis')->has('GROUPCHAT:MSG:ADMIN:READ')) {
            Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', [], 0);
            $reads = [];
        } else {
            $reads = Cache::store('redis')->get('GROUPCHAT:MSG:ADMIN:READ', []);
        }

        foreach ($group_list as &$value) {
            if (!empty($unreadMessage[$value['anchor_id'] . '_' . $value['id']])) {
                if (!empty($reads[$value['anchor_id'] . '_' . $value['id']])) {
                    $value['unread_message'] = $unreadMessage[$value['anchor_id'] . '_' . $value['id']] - $reads[$value['anchor_id'] . '_' . $value['id']];
                } else {
                    $value['unread_message'] = $unreadMessage[$value['anchor_id'] . '_' . $value['id']];
                    $reads[$value['anchor_id'] . '_' . $value['id']] = 0;
                }

                if ($value['unread_message'] > 99) {
                    $value['unread_message'] = '99+';
                }
            } else {
                $value['unread_message'] = 0;
            }
        }

        Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', $reads, 0);

        return $this->assign([
            'group_list' => $group_list,
            'anchor_id' => $anchor_id,
            'count' => count($group_list),
            'private_chat_ws' => getConfigPub()->private_chat_ws,
            'supertube' => in_array($this->userinfo->roleid, [1, 11]) ? 1 : 0,
            'admin_user_id' => $this->admin_id,
        ])->fetch();
    }

    /**
     * 获取用户聊天状态
     */
    public function get_group_info()
    {
        $group_id = Request::get('group_id', 0, 'intval');

        if ($group_id < 1) {
            return json(['info' => [], 'code' => 1]);
        }

        // 获取基本信息
        $group_info = GroupChatModel::get($group_id);
        if (empty($group_info)) {
            return json(['info' => [], 'code' => 1]);
        }

        return json(['info' => $group_info, 'code' => 0]);
    }

    /**
     * 获取聊天内容
     */
    public function get_chat_content()
    {
        $group_id = Request::get('group_id');
        $send_time = Request::get('send_time');
        $sort = Request::get('sort', 'desc');

        if (!$model = GroupChatModel::where('id', $group_id)->find()) {
            return json(['list' => [], 'code' => 0]);
        }

        $unreadMessage = Cache::store('redis')->handler()->hGetAll('GROUPCHAT:MSG:NUM') ?: [];
        if (!Cache::store('redis')->has('GROUPCHAT:MSG:ADMIN:READ')) {
            Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', [], 0);
            $reads = [];
        } else {
            $reads = Cache::store('redis')->get('GROUPCHAT:MSG:ADMIN:READ', []);
        }

        if (!empty($unreadMessage[$model->anchor_id . '_' . $model->id])) {
            $reads[$model->anchor_id . '_' . $model->id] = $unreadMessage[$model->anchor_id . '_' . $model->id];
            Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', $reads, 0);
        }

        try {
            // es查询条件
            $options = [
                'index' => 'fans_group_history',
                'size' => 30,
                'from' => 0,
                'sort' => ['send_time' => 'desc'],
                'where' => [
                    ['group_id', '=', $model->anchor_id . '_' . $group_id],
                    ['type', 'IN', [0, 7]]
                ],
            ];
            if ($sort) {
                $options['sort'] = ['send_time' => $sort];
            }
            // 从那个时间开始查询
            if ($send_time) {
                if ($sort == 'asc') {
                    $options['where'][] = ['send_time', '>', $send_time];
                } else {
                    $options['where'][] = ['send_time', '<', $send_time];
                }
            }

            // 获取数据
            $es_client = new Esclient();
            $response = $es_client->search($options);
            $data = $response['data'];

            foreach ($data as &$value) {
                $value['seq'] = strval($value['seq']);
            }

            if (empty($data)) {
                return json(['list' => [], 'code' => 0]);
            }

            // 如果是倒序，数组翻转
            if ($sort == 'desc') {
                $data = array_reverse($data);
            }
            return json(['list' => $data, 'code' => 0]);
        } catch (\Exception $e) {

        }
        return json(['list' => [], 'code' => 0]);
    }

    /**
     * 异步获取和主播正在私聊的用户列表
     * @return \think\response\Json|void
     */
    public function get_group_list()
    {
        $anchor_id = Request::get('anchor_id', 0, 'intval');
        if ($anchor_id < 1) {
            return json(['list' => [], 'code' => 1]);
        }

        $anchor_id = Request::get('anchor_id', 0, 'intval');
        // 查询私聊历史信息
        $where = [
            ['anchor_id', '=', $anchor_id],
            ['status', '=', 0],
        ];
        $group_list = GroupChatModel::with([
            'anchor' => function ($query) {
                $query->field('id,nick_name');
            },
        ])->where($where)->order('id', 'DESC')
            ->select()
            ->toArray();

        $unreadMessage = Cache::store('redis')->handler()->hGetAll('GROUPCHAT:MSG:NUM') ?: [];
        if (!Cache::store('redis')->has('GROUPCHAT:MSG:ADMIN:READ')) {
            Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', [], 0);
            $reads = [];
        } else {
            $reads = Cache::store('redis')->get('GROUPCHAT:MSG:ADMIN:READ', []);
        }

        if (ctype_digit($group_id = $this->get('group_id')) && $group_id > 0 && !empty($unreadMessage[$anchor_id . '_' . $group_id])) {
            $reads[$anchor_id . '_' . $group_id] = $unreadMessage[$anchor_id . '_' . $group_id];
        }

        foreach ($group_list as &$value) {
            if (!empty($unreadMessage[$value['anchor_id'] . '_' . $value['id']])) {
                if (!empty($reads[$value['anchor_id'] . '_' . $value['id']])) {
                    $value['unread_message'] = $unreadMessage[$value['anchor_id'] . '_' . $value['id']] - $reads[$value['anchor_id'] . '_' . $value['id']];
                } else {
                    $value['unread_message'] = $unreadMessage[$value['anchor_id'] . '_' . $value['id']];
                    $reads[$value['anchor_id'] . '_' . $value['id']] = 0;
                }

                if ($value['unread_message'] > 99) {
                    $value['unread_message'] = '99+';
                }
            } else {
                $value['unread_message'] = 0;
            }
        }

        Cache::store('redis')->set('GROUPCHAT:MSG:ADMIN:READ', $reads, 0);

        return json(['group_list' => $group_list, 'count' => count($group_list), 'code' => 0]);
    }

    /**
     * 发送聊天内容
     * @return \think\response\Json
     */
    public function send_chat()
    {
        $all_param = Request::param();

        $validate = new Validate([
            'group_id' => 'require|number',
        ], [
            "group_id" => "会话参数错误",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $content = trim($this->post('content', ''));
        if (!$img = trim($this->post('img', ''))) {
            if (empty($content)) {
                return parent::bulidFail('消息内容不能为空');
            }
        } else {
            if (mb_strpos($img, 'http') !== 0) {
                return parent::bulidFail('您发送的图片错误');
            }
        }

        if (mb_strlen($content) > 300) {
            return parent::bulidFail('消息内容不能超过300个字符');
        }

        // 获取单条基本信息
        $group_info = GroupChatModel::with([
            'anchor' => function ($query) {
                $query->field('id,nick_name');
            },
        ])->get($all_param['group_id']);

        if (empty($group_info)) {
            return parent::bulidFail('群聊不存在');
        }

        if ($group_info->status != 0) {
            return parent::bulidFail('群聊会话已解散');
        }

        // 权限判断
        $check_chat_admin = PrivatechatService::checkAdminChat($this->userinfo->roleid, $this->admin_id, $group_info->anchor_id);
        if ($check_chat_admin['code'] != 0) {
            return parent::bulidFail('你当前没有权限回复该群组聊天');
        }

        // 调取grpc
        $tim_server = new TencentTimServer();
        if ($img) {
            $tim_res = $tim_server->sendGroupChatMsg($this->admin_id, $group_info->id, $content, $img);
        } else {
            $tim_res = $tim_server->sendGroupChatMsg($this->admin_id, $group_info->id, $content);
        }

        if (!$tim_res) {
            return json(['list' => [], 'code' => 1, 'msg' => '发送失败',]);
        }

        $data = [
            'seq' => $tim_res,
            'role' => 1,
            "uid" => $group_info->anchor_id,
            "group_id" => $group_info->id,
            "nick_name" => $group_info->anchor ? $group_info->anchor->nick_name : '',
            "content" => $content,
            "send_time" => time(),
        ];

//        GatewayWorkerService::sendMsg('group_say', $data);
//        //
//        $data = [
//            'seq'=>time().rand(1,10000),
//            'role'=>1,
//            "uid"       => 600001,
//            "group_id"  => $group_info->id,
//            "nick_name" => '测试',
//            "content"   => $all_param['content'],
//            "send_time" => getMicrotime(),
//        ];
//
//        GatewayWorkerService::sendMsg('group_say', $data);

        return json(['list' => $data, 'code' => 0, 'msg' => '']);
    }


    /**
     * 群聊内容
     */
    public function chat_content()
    {
        if (!ctype_digit($id = $this->get('id', ''))) {
            return static::bulidFail('ID非法');
        }
        if (!$model = PrivateChatSessionModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的私聊信息');
        }

        if ($this->request->isAjax()) {
            $page = (int)$this->get('page', 1);
            $where = [
                'index' => 'private_history',
                'size' => $limit = (int)$this->get('limit', 20),
                'from' => ($page - 1) * $limit,
                'where' => [
                    ['session_id', '=', $model->id]
                ],
                'sort' => ['send_time' => 'desc']
            ];

            $list = (new Esclient())->search($where);
            $nick_names = UserModel::whereIn('id', array_column($list['data'], 'sender_uid'))->column('nick_name', 'id');
            foreach ($list['data'] as &$value) {
                $value['nick_name'] = $nick_names[$value['sender_uid']] ?? $value['sender_uid'];
                $value['send_time'] = date('Y-m-d H:i:s', bcdiv($value['send_time'], '1000', 0));
            }
            return json([
                'count' => $list['total'],
                'pageCount' => ceil($list['total'] / $limit),
                'list' => $list['data'],
                'code' => 0,
                'page' => $page,
            ]);
        }
        return $this->assign(['model' => $model])->fetch();
    }

    /**
     * 解散群聊
     */
    public function dissolve()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id,anchor_id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        $grpc = new TencentTimServer();
        if ($grpc->dissolveGroupChat($group_id)) {
            $this->addAdminLog("在后台为{$model->anchor_id}解散了一个群聊,群聊ID:{$model->id}", $model->anchor_id);
            return static::bulidSuccess([], '解散群聊成功');
        }

        return static::bulidFail('解散群聊失败');
    }

    /**
     * 移除用户-踢人操作
     */
    public function kick_user()
    {
        // post参数  user_ids  group_id
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!$user_ids = rtrim(trim($this->post('user_ids', '')), ',')) {
            return static::bulidFail('请选择您要踢出群聊的用户!');
        }

        $user_ids = explode(',', $user_ids);
        $insert = [];
        foreach ($user_ids as $id) {
            if (!ctype_digit($id)) {
                return static::bulidFail('您当前操作存在非法用户');
            }
            $insert[] = [
                'adminid' => $this->admin_id,
                'content' => $this->admin_name . '在后台移除了用户:' . $id,
                'create_time' => date('Y-m-d H:i:s'),
                'uid' => $id,
            ];
        }

        $grpc = new TencentTimServer();
        if ($grpc->kickUser($group_id, $user_ids)) {
            (new AdminLogModel)->saveAll($insert);
            return static::bulidSuccess([], '踢出用户成功');
        }

        return static::bulidFail('踢出用户失败');
    }

    /**
     * 编辑群组
     */
    public function edit()
    {
        if (!ctype_digit($group_id = $this->get('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('群聊名称不能为空');
            }

            if (strlen($name) > 30) {
                return static::bulidFail('群聊名称不能超过30个字节长度 一个中文占三个字节');
            }

            if (!$avatar = trim($this->post('avatar', ''))) {
                return static::bulidFail('群头像不能为空');
            }

            if (!filter_var($avatar, FILTER_VALIDATE_URL)) {
                return static::bulidFail('群头像地址错误');
            }

            $introduce = trim($this->post('introduce', ''));
            $welcome_desc = trim($this->post('welcome_desc', ''));

            if (mb_strlen($introduce) > 200) {
                return static::bulidFail('群介绍不能超过200个字符');
            }

            if (mb_strlen($welcome_desc) > 200) {
                return static::bulidFail('欢迎语不能超过200个字符');
            }

            $model->name = $name;
            $model->avatar = $avatar;
            $model->introduce = $introduce;
            $model->welcome_desc = $welcome_desc;

            if ($model->save()) {
                Cache::store('redis')->handler()->hDel('GROUPCHAT:DATA', $group_id, $model->anchor_id . '_' . $group_id);
                $this->addAdminLog("编辑了主播ID:{$model->anchor_id}下的群聊ID:{$model->id}群聊信息", $model->anchor_id);
                return static::bulidSuccess([], '编辑成功');
            }

            return static::bulidFail('编辑失败');
        }

        return $this->assign(['model' => $model])->fetch();
    }

    /**
     * 详情初始化页面
     * @return mixed
     */
    public function chat_info_default()
    {
        return $this->fetch();
    }

    public function anchor_list()
    {
        if ($this->request->isAjax()) {
            if (ctype_digit($anchor_id = $this->get('anchor_id', ''))) {
                if (!$user = UserModel::field('id,nick_name')->where('id', $anchor_id)->find()) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                        'msg' => '查无数据',
                    ]);
                }

                if (!$fans_group_num = GroupChatModel::where('anchor_id', $user->id)->count('id')) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                        'msg' => '查无数据',
                    ]);
                }

                return json([
                    'count' => 1,
                    'list' => [
                        [
                            'serial_num' => 1,
                            'anchor_id' => $user->id,
                            'anchor_name' => $user->nick_name,
                            'fans_group_num' => GroupChatModel::where('anchor_id', $user->id)->count('id'),
                            'fans_num' => GroupChatModel::where('anchor_id', $user->id)->sum('user_num')
                        ]
                    ],
                    'code' => 0,
                    'msg' => '',
                ]);
            }

            $page = (int)$this->get('page', 1);
            $limit = (int)$this->get('limit', 20);

            $number = ($page - 1) * $limit;

            if ($anchor_name = trim($this->get('anchor_name', ''))) {
                if (!$userData = UserModel::field('id,nick_name')->whereLike('nick_name', $anchor_name . '%')->select()->toArray()) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                        'msg' => '查无数据',
                    ]);
                }

                $model = GroupChatModel::field('anchor_id,count(id) as fans_group_num, sum(user_num) as fans_num')
                    ->whereIn('anchor_id', array_column($userData, 'id'))
                    ->group('anchor_id');
                $list = $model->page($page, $limit)
                    ->select()
                    ->toArray();
                $userData = array_column($userData, 'nick_name', 'id');
            } else {
                $model = GroupChatModel::field('anchor_id,count(id) as fans_group_num, sum(user_num) as fans_num')
                    ->group('anchor_id');
                if (!$list = $model->page($page, $limit)
                    ->select()
                    ->toArray()) {
                    $userData = [];
                } else {
                    $userData = UserModel::field('id,nick_name')
                        ->whereIn('id', array_column($list, 'anchor_id'))
                        ->column('nick_name', 'id');
                }
            }

            foreach ($list as &$value) {
                $number++;
                $value['serial_num'] = $number;
                $value['anchor_name'] = $userData[$value['anchor_id']] ?? $value['anchor_id'];
            }

            return json([
                'count' => $model->count('anchor_id'),
                'list' => $list,
                'code' => 0,
                'msg' => '',
            ]);
        }

        return $this->fetch();
    }

    public function anchor_info()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail('ID非法');
        }

        if (!$user = UserModel::field('id,nick_name')->where('id', $id)->find()) {
            return static::bulidFail('主播不存在');
        }

        $list = GroupChatModel::where('anchor_id', $id)
            ->order('id', 'desc')
            ->select()
            ->toArray();

        $admin_ids = array_column($list, 'create_admin_id');
        $admin_ids = array_unique($admin_ids);
        $admin_names = AdminModel::whereIn('id', $admin_ids)->column('account', 'id');

        foreach ($list as &$value) {
            $value['nick_name'] = $user->nick_name;
            $value['admin_name'] = $admin_names[$value['create_admin_id']] ?? '';
        }

        return $this->assign([
            'list' => $list,
            'user' => $user,
        ])->fetch();
    }

    public function user_list()
    {

        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID非法');
        }

        $model = GroupChatUserModel::field('id,user_id,role')->where('group_id', $group_id);

        return json([
            'count' => $count = $model->count('id'),
            'list' => $model->with([
                'user' => function (Query $query) {
                    $query->field('id,nick_name,avatar');
                },
            ])->order(['role' => 'desc', 'id' => 'desc'])
                ->page($page = $this->post('page', 1), 20)
                ->select()->each(function ($query) {
                    if ($query->role == 1) {
                        $query->user->nick_name = $query->user->nick_name . '(房管)';
                    } else if ($query->role == 2) {
                        $query->user->nick_name = $query->user->nick_name . '(群主)';
                    }
                })
                ->toArray(),
            'code' => 0,
            'msg' => '',
            'page' => $page,
            'pageCount' => ceil($count / 20),
        ]);
    }

    /**
     * 获取群聊用户列表
     * @return \think\response\Json
     */
    public function group_user_list()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID非法');
        }

        if (!$groupChat = GroupChatModel::field('id', 'anchor_id')->where('id', $group_id)->find()) {
            return json([
                'count' => 0,
                'list' => [],
                'code' => 0,
                'msg' => '',
            ]);
        }

        $model = GroupChatUserModel::where('group_id', $group_id);

        $user_name = $this->post('user_name');
        if (mb_strlen($user_name, 'UTF-8') > 0) {
            if (ctype_digit($user_name)) {
                $uid_arr = UserModel::whereLike('id', $user_name . '%')->column('id');
            } else {
                $uid_arr = UserModel::whereLike('nick_name', $user_name . '%')->column('id');
            }

            $model->whereIn('user_id', $uid_arr);
        }

        $list = $model->with([
            'user' => function (Query $query) {
                $query->field('id,nick_name,avatar');
            },
        ])->order('role', 'desc')
            ->select()
            ->toArray();

        $bannedUsers = [];
        if ($uids = array_column($list, 'user_id')) {
            $bannedUsers = LiveRoomBanneduserModel::whereIn('uid', $uids)
                ->column('ban_time', 'uid');
        }

        $data = [];
        foreach ($list as &$item) {
            $other_name = $item['user']['nick_name'];
            if ($item['role'] == 2) {
                $other_name .= '(群主)';
            } else if ($item['role'] == 1) {
                $other_name .= '(房管)';
            }

            $status = 0;
            if (!empty($bannedUsers[$item['user_id']])) {
                if ($bannedUsers[$item['user_id']] > time()) {
                    $status = 1;
                }
            }
            $data[] = [
                'id' => $item['id'],
                'user_id' => $item['user_id'],
                'nick_name' => $item['user']['nick_name'],
                'other_name' => $other_name,
                'avatar' => $item['user']['avatar'],
                'group_id' => $item['group_id'],
                'role' => $item['role'],
                'status' => $status,
            ];
        }
        unset($list);

        return json([
            'count' => $model->count('id'),
            'list' => $data,
            'code' => 0,
            'msg' => '',
        ]);
    }

    public function chat_log()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID非法');
        }

        $page = (int)$this->post('page', 1);
        if (!$model = GroupChatModel::where('id', $group_id)->find()) {
            return json([
                'count' => 0,
                'list' => [],
                'code' => 0,
                'page' => $page,
                'pageCount' => 0,
            ]);
        }

        $where = [
            'index' => 'fans_group_history',
            'size' => $limit = 20,
            'from' => ($page - 1) * $limit,
            'where' => [
                ['group_id', '=', $model->anchor_id . '_' . $group_id],
                ['type', 'IN', [0, 7]]
            ],
            'sort' => ['send_time' => 'desc']
        ];

        if ($content = trim($this->post('content', ''))) {
            $where['where'][] = ['content', 'LIKE', "%" . $content . "%"];
        }

        $list = (new Esclient())->search($where);
        foreach ($list['data'] as &$value) {
            $value['seq'] = strval($value['seq']);
            if (!empty($value['send_time'])) {
                $value['send_time'] = date('Y-m-d H:i:s', $value['send_time']);
            }
        }

        return json([
            'count' => $list['total'],
            'list' => $list['data'],
            'code' => 0,
            'page' => $page,
            'pageCount' => ceil($list['total'] / $limit),
        ], 200, [], ['json_encode_param' => 512]);
    }

    public function add()
    {
        if (!ctype_digit($anchor_id = $this->get('anchor_id'))) {
            return static::bulidFail('主播ID错误');
        }

        if (!$user = UserModel::field('id')->where('id', $anchor_id)->find()) {
            return static::bulidFail('主播不存在');
        }

        if ($this->request->isAjax()) {
            if (GroupChatModel::where('anchor_id', $anchor_id)->where('status', 0)->count('id') > 10) {
                return static::bulidFail('当前主播创建群聊不能超过10个');
            }

            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('群聊名称不能为空');
            }

            if (strlen($name) > 30) {
                return static::bulidFail('群聊名称不能超过30个字节长度 一个中文占三个字节');
            }

            if (!$avatar = trim($this->post('avatar', ''))) {
                return static::bulidFail('群头像不能为空');
            }

            if (!filter_var($avatar, FILTER_VALIDATE_URL)) {
                return static::bulidFail('群头像地址错误');
            }

            $introduce = trim($this->post('introduce', ''));
            $welcome_desc = trim($this->post('welcome_desc', ''));

            if (mb_strlen($introduce) > 200) {
                return static::bulidFail('群介绍不能超过200个字符');
            }

            if (mb_strlen($welcome_desc) > 200) {
                return static::bulidFail('欢迎语不能超过200个字符');
            }

            $grpc = new TencentTimServer();
            if ($group_id = $grpc->createGroupChat($this->admin_id, $user->id, $name, $avatar, $introduce, $welcome_desc)) {
                $this->addAdminLog("在后台为{$user->id}创建了一个群聊,群聊ID为:{$group_id}", $user->id);
                return static::bulidSuccess([], '创建成功');
            }

            return static::bulidFail('创建失败');
        }

        return $this->assign(['anchor_id' => $user->id])->fetch();
    }

    /**
     * 设置房管
     */
    public function set_manage()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!ctype_digit($uid = $this->post('user_id'))) {
            return static::bulidFail('用户ID非法');
        }

        if (!$user = UserModel::field('id')->where('id', $uid)->find()) {
            return static::bulidFail('不存在的用户');
        }

        $grpc = new TencentTimServer();
        if ($grpc->assignGroupChatAdmin($model->id, $user->id)) {
            $this->addAdminLog("在后台群聊设置用户:{$user->id}为房管", $user->id);
            return static::bulidSuccess([], '设置房管成功');
        }

        return static::bulidFail('设置房管失败');
    }

    /**
     * 取消房管
     */
    public function cancel_manage()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!ctype_digit($uid = $this->post('user_id'))) {
            return static::bulidFail('用户ID非法');
        }

        if (!$user = UserModel::field('id')->where('id', $uid)->find()) {
            return static::bulidFail('不存在的用户');
        }

        $grpc = new TencentTimServer();
        if ($grpc->cancelAssignGroupChatAdmin($model->id, $user->id)) {
            $this->addAdminLog("在后台群聊取消用户:{$user->id}为房管", $user->id);
            return static::bulidSuccess([], '取消房管成功');
        }

        return static::bulidFail('取消房管失败');
    }

    /**
     * 取消房管
     */
    public function revoke_message()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!$msg_id = $this->post('msg_id')) {
            return static::bulidFail('参数错误');
        }

        $grpc = new TencentTimServer();
        if ($grpc->revokeMessage($model->id, $msg_id)) {
            return static::bulidSuccess([], '撤回成功');
        }

        return static::bulidFail('撤回失败');
    }

    public function ban_user()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!ctype_digit($uid = $this->post('user_id'))) {
            return static::bulidFail('用户ID非法');
        }

        if (!$user = UserModel::field('id')->where('id', $uid)->find()) {
            return static::bulidFail('不存在的用户');
        }

        if (!in_array($ban_time = $this->post('time'), ['10', '30', '60', '120', '360', '1440', '10080', '-1'])) {
            return static::bulidFail('禁言时间选择错误');
        }

        $ban_time = (int)$ban_time;

        if (!in_array($reason = $this->post('reason'), ['涉政言论', '广告营销诈骗', '低俗色情', '不实信息', '违法有害信息', '辱骂谩骂', '其他'])) {
            return static::bulidFail('禁言理由选择错误');
        }

        if ($banneduser = LiveRoomBanneduserModel::where('uid', $user->id)->find()) {
            if ($banneduser->ban_time < 0) {
                return json(["code" => 1000, "msg" => '用户已是禁言状态 禁言时间截止:永久']);
            }
            if ($banneduser->ban_time > time()) {
                return json(["code" => 1000, "msg" => '用户已是禁言状态 禁言时间截止:' . date('Y-m-d H:i:s', $banneduser->ban_time)]);
            }
        }

        $grpc = new TencentTimServer();
        if ($grpc->banUser($model->id, $user->id, $ban_time, $reason, array_flip(LiveRoomBanneduserModel::BAN_TYPE)[$reason], $this->admin_id)) {
            $log_content = "在后台群聊禁言用户，用户ID：{$user->id}，原因：" . $reason . '，禁言时长：';
            // 腾讯im禁言时长
            switch ($ban_time) {
                case '-1':
                    $log_content .= '永久';
                    break;
                case '10':
                    $log_content .= '十分钟';
                    break;
                case '30':
                    $log_content .= '半小时';
                    break;
                case '120':
                    $log_content .= '两小时';
                    break;
                case '360':
                    $log_content .= '6小时';
                    break;
                case '1440':
                    $log_content .= '一天';
                    break;
                case '10080':
                    $log_content .= '七天';
                    break;
            };
            $this->addAdminLog($log_content, $user->id);
            return static::bulidSuccess([], '设置禁言成功');
        }

        return static::bulidFail('设置禁言失败');
    }

    /**
     * 解除禁言
     */
    public function un_banned_user()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$model = GroupChatModel::field('id,anchor_id')->where('id', $group_id)->find()) {
            return static::bulidFail('不存在的群组');
        }

        if (!ctype_digit($uid = $this->post('user_id'))) {
            return static::bulidFail('用户ID非法');
        }

        if (!$user = UserModel::field('id')->where('id', $uid)->find()) {
            return static::bulidFail('不存在的用户');
        }

        $grpc = new TencentTimServer();
        if ($grpc->cancelBanUser($model->anchor_id . '_' . $model->id, $uid, $model->anchor_id)) {
            $this->addAdminLog("在后台群聊解除禁言, 解禁用户:{$uid}", $uid);
            return static::bulidSuccess([], '解除禁言成功');
        }

        return static::bulidFail('解除禁言失败');
    }

    public function del_message()
    {
        if (!ctype_digit($group_id = $this->post('group_id'))) {
            return static::bulidFail('群ID错误');
        }

        if (!$msg_id = trim($this->post('msg_id', ''))) {
            return static::bulidFail('消息ID不能为空');
        }

        $grpc = new TencentTimServer();
        if ($grpc->deleteMessage($group_id, $msg_id, $this->admin_id, $this->admin_name)) {
            return static::bulidSuccess([], '删除用户消息成功');
        }

        return static::bulidFail('删除用户消息失败');
    }

    public function mgr()
    {
        $sql = "SELECT a.*,b.id as user_id,b.nick_name,b.avatar,c.count FROM live.db_live_room_manager a left join main.db_user b on a.mgrid = b.id left join (select count(id) as count,mgr_id from main.db_mgr_chat where 1=1 GROUP BY mgr_id) c on a.mgrid=c.mgr_id";
        $list = DB::query($sql);
        foreach ($list as $key => &$value) {
            if (!$value['count']) {
                $value['count'] = 0;
            }
            if (!$value['user_id']) {
                unset($list[$key]);
            }
        }
        return $this->assign(['list' => $list, 'count' => count($list)])->fetch();
    }

    public function mgr_user_list()
    {
        if (!ctype_digit($mgrid = $this->post('mgrid'))) {
            return json([
                'count' => 0,
                'list' => [],
                'code' => 0,
                'msg' => 'mgrid参数错误',
                'pageCount' => 0,
            ]);
        }

        if (!$user = LiveRoomManagerModel::field('mgrid')->where('mgrid', $mgrid)->find()) {
            return json([
                'count' => 0,
                'list' => [],
                'code' => 0,
                'msg' => '房管不存在',
                'pageCount' => 0,
            ]);
        }

        $model = $mgrChat = MgrChatModel::field('*')->where('mgr_id', $mgrid);
        if ($user_name = trim($this->post('user_name', ''))) {
            if (ctype_digit($user_name)) {
                $model = $model->whereLike('user_id', $user_name . '%');
            } else {
                if (!$ids = UserModel::whereLike('nick_name', $user_name . '%')->column('id')) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                        'msg' => '',
                        'pageCount' => 0,
                    ]);
                }
                $model = $model->whereIn('user_id', $ids);
            }
        }

        return json([
            'count' => $count = $model->count('id'),
            'list' => $model->with('user')
                ->order('id', 'desc')
                ->page($this->post('page', 1), 30)
                ->select()
                ->toArray(),
            'code' => 0,
            'pageCount' => ceil($count / 30),
            'msg' => '',
        ]);
    }

    public function mgr_chat_log()
    {
        if (!ctype_digit($mgr_id = $this->post('mgr_id'))) {
            return static::bulidFail('房管ID非法');
        }

        if (!ctype_digit($user_id = $this->post('user_id'))) {
            return static::bulidFail('用户ID非法');
        }

        $page = (int)$this->post('page', 1);
        $where = [
            'index' => 'mgr_history',
            'size' => $limit = 30,
            'from' => ($page - 1) * $limit,
            'where' => [
                ['chat_id', '=', $mgr_id . '_' . $user_id],
                //['text_type', '=', 0]
            ],
            'sort' => ['send_time' => 'desc']
        ];

        if ($content = trim($this->post('content', ''))) {
            $where['where'][] = ['content', 'LIKE', "%" . $content . "%"];
        }

        $list = (new Esclient())->search($where);
        foreach ($list['data'] as &$value) {
            if (!empty($value['id'])) {
                $value['id'] = strval($value['id']);
            }
            if (!empty($value['send_time'])) {
                $value['send_time'] = date('Y-m-d H:i:s', $value['send_time']);
            }
        }
        return json([
            'count' => $list['total'],
            'list' => $list['data'],
            'code' => 0,
            'page' => $page,
            'pageCount' => ceil($list['total'] / $limit),
        ]);
    }

    public function del_mgr_message()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('删除消息参数错误');
        }


        $grpc = new TencentTimServer();
        if ($grpc->delMgrSingleMsg($id)) {
            return static::bulidSuccess([], '删除消息成功');
        }

        return static::bulidFail('删除消息失败');
    }
}